package com.novel.listen;

import com.novel.config.RedissonHelper;
import com.novel.entiy.Novel;
import com.novel.entiy.event.HotEvent;
import com.novel.mapper.NovelMapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 热度变化监听
 *
 * @author chihuo
 * @date 2022/4/11
 */
@Slf4j
@Component
public class HotNumListen {

    @Resource
    private NovelMapper novelMapper;

    @Resource
    private RedissonHelper redissonHelper;

    /**
     * 监听热度变化
     *
     * @param hotEvent 热度变化事件
     */
    @EventListener(HotEvent.class)
    public void onApplicationEvent(HotEvent hotEvent) {
        hotNums(hotEvent);
    }

    public void hotNums(HotEvent hotEvent) {
        Long novelId = hotEvent.getNovelId();
        RLock lock = redissonHelper.getLock("hot_num" + novelId);
        try {
            if (lock.tryLock(100, 10000, TimeUnit.MILLISECONDS)) {
                try {
                    Novel novel = novelMapper.selectById(novelId);
                    novel.setHotNums(novel.getHotNums() + hotEvent.getHotNums());
                    novelMapper.updateById(novel);
                } finally {
                    lock.unlock();
                }
            } else {
                hotNums(hotEvent);
            }
        } catch (InterruptedException e) {
            log.error("热度值变化失败 novelId:{}", novelId, e);
        }
    }

}
